<template>
  <base-modal
    :title="title"
    :show="visible"
    width="800px"
    class="task-initiate-dialog"
    @cancel="visible = false"
  >
     <!--  表单  -->
    <div class="task-initiate-dialog-form">
      <form-builder
        class="bbx-cell-form-builder"
        ref="taskInitiateRef"
        mode="taskInitiate"
        formStatus="edit"
        formEditingMode="edit"
        :fields="fields"
        :value="formValue"
        :form-cell-count="2"
        @getDeleteFiles="getDeleteFiles"
        @update="updateForm"
      >

      </form-builder>
    </div>
    <div slot="footer" class="dialog-footer">
      <div class="dialog-footer-right">
        <el-button type="plain-third" @click="visible = false" :disabled="pending || pendingStorage">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="plain-third" @click="toTemporaryStorage" :disabled="pending || pendingStorage">{{ $t('common.base.temporaryStorage') }}</el-button>
        <el-button type="primary" @click="submitCustomNode" :disabled="pendingStorage" :loading="pending">{{ $t('common.base.makeSure') }}</el-button>
      </div>
    </div>
  </base-modal>
</template>

<script>
/* api*/
import  {checkNeedVipApprove, saveCustomNode, draftSaveCustomerNode } from '@src/api/TaskApi.ts'
/* utils*/
import _ from "lodash";
import * as FormUtil from "@form/util";
import {useFormTimezone} from "pub-bbx-utils";
const { disposeFormSubmitTime } = useFormTimezone()


export default {
  name: "InitiateDialog",
  props: {
    taskId: {
      type: String,
      default: ''
    },
    nodeId: {
      type: String,
      default: ''
    },
    currentNodeId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fields: [],
      loading: false,
      pending: false,
      pendingStorage: false,
      title: '',
      visible: false,
      formValue: {},
      needServerDelFiles: [],
      isStartNode: false, // 判断是否是开始节点
    }
  },
  methods: {
    // 删除的附件
    getDeleteFiles(files) {
      this.needServerDelFiles = [...this.needServerDelFiles, ...files]
    },
    // 更新表单字段
    updateForm({ field, newValue, oldValue }) {
      if(!field) return
      const { fieldName = '', displayName = '' } = field || {};

      this.$set(this.formValue, fieldName, newValue);
    },

    // 打开弹框
    async openCustomNodeDialog(fields = [], nodeName, task, temporaryStorageVal = {}, isStartNode = false) {
      try {
        this.title = this.$t('common.task.customTitle', { nodeName })
        this.fields = fields;
        this.isStartNode = isStartNode;
        // 获取引用字段值
        let val = _.cloneDeep(task.attribute)
        let formDate = {};
        // 只传this.fields的值，所以formDate接收下
        this.fields?.forEach(item => {
          // 如果暂存存过，用暂存的值，否则用工单详情的值
          if(item.fieldName in temporaryStorageVal) {
            this.$set(formDate, item.fieldName,  temporaryStorageVal[item.fieldName])
          }else {
            val?.[item.fieldName] && this.$set(formDate, item.fieldName, val[item.fieldName])
          }
        })
        this.formValue = FormUtil.initialize(this.fields, formDate);
        this.$nextTick(() => {
          this.visible = true
        })
      } catch (e) {
        console.error(e)
      }

    },
    closeDialog() {
      this.pending= false;
      this.visible = false;
    },
    // 提交表单
    async submitCustomNode() {
      // 校验必填
      try {
        this.pending= true;

        const valid = await this.$refs.taskInitiateRef?.validate(false)

        if (!valid) return this.pending= false;
      } catch (e) {
        console.error(e)
      }
      // 提交
      try {

        let formData = disposeFormSubmitTime(this.fields, this.formValue) // 处理国际化时间转换


        const params = {formData, needServerDelFiles: this.needServerDelFiles}
        // 开始工单处理
        if(this.isStartNode) return this.$emit('start', params, this.closeDialog)

       /* start 完成节点前校验高级审批*/
        const { success: suc, result, message: msg } = await checkNeedVipApprove({
          nodeFormData: formData,
          taskId: this.taskId,
          action: 'nodeTask',
          nodeTaskBizId: this.currentNodeId,
        });
        if(!suc) {
          this.pending= false;
          return this.$message.error(msg)
        }
        // 需要高级审批
        if (suc && result?.needVipApprove) {
          this.pending= false;
          this.$emit('proposeApprove', result ?? {})
          return
        }
        /* end 完成节点前校验高级审批*/

        // 提交节点信息
        const { success, message} = await saveCustomNode({
          taskId: this.taskId,
          ...params,
          currentNodeId: this.currentNodeId
        })
        this.pending= false;

        if(!success) return this.$message.error(message);

        window.location.href = `${this.$resourcePrefix}/task/view/${this.taskId}`;

      } catch (e) {
        console.error(e)
        this.pending= false;
      } finally {
        this.visible = false;
      }
    },

    /*暂存表单*/
    async toTemporaryStorage() {
      try {
        this.pendingStorage = true;

        const formData = disposeFormSubmitTime(this.fields, this.formValue) // 处理国际化时间转换

        const params = {
          taskId: this.taskId,
          currentNodeId: this.isStartNode ? 'start' : this.currentNodeId,
          formData,
        }
        const { success, message } = await draftSaveCustomerNode(params)

        if(!success) return this.$message.error(message);

        this.$message.success(this.$t('common.base.temporarySaveSuccess'));

        this.visible = false;
      } catch (e) {
        console.error(e)
      } finally {
        this.pendingStorage = false;
      }
    },
  },
}
</script>

<style lang="scss">
.task-initiate-dialog {
  &-form {
    .form-builder {
      width: unset;
    }
  }
}
</style>